<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('开启规格')"/>
    <!--<th:block th:include="include :: datetimepicker-css" />-->
</head>

<body class="gray-bg">
<div id="dialogSpec" style="padding: 0 15px">
    <div style="min-width: 600px;">
        <div style="min-height: 300px;">
            <div class="row">
                <div class="col-xs-12" style="float: left">
                    <div id="specParent">


                        <div class="spec" th:each="spList : ${specList}"
                             style="float: left;padding-right: 10px;padding-left: 10px"
                             th:attr="data-spec-name=${spList.goodsSpec.name},data-spec-id=${spList.goodsSpec.id}">
                            <span class="h5 mb10" style="float: left"><input class="specChkAll" type="checkbox"><strong
                                    th:text="${spList.goodsSpec.name}"></strong></span>
                            <div style="float: left;padding-left: 20px;">

                                <div class="vl" th:each="sVList : ${spList.typeSpecValueDtoList}">
                                    <input th:id="${sVList.specValueId}" type="checkbox"
                                           th:value="${sVList.specValueId}"
                                           th:title="${sVList.value}"><span th:text="${sVList.value}"></span>
                                </div>

                            </div>
                        </div>

                    </div>
                </div>
                <div class="col-xs-12" style="padding-top: 5px;height: 45px;">
                    <button id="doProduct" type="button" class="btn btn-primary btn-sm">生成所有货品</button>
                </div>
                <div style="width: 100%;text-align: center;margin-top: 10px;">
                    <table id="plist" class="table table-bordered table-striped table-condensed"
                           style="width: 95%;margin: 20px;">
                        <thead>
                        <tr>
                            <th>规格值</th>
                            <!-- <th class="numeric">上架</th> -->
                            <th class="numeric">图片(133*133)</th>
                            <th class="numeric">原价(元)</th>
                            <th class="numeric">现价(积分)</th>
                            <th class="numeric">库存</th>
                            <th class="numeric">默认货品</th>
                        </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">取 消</button>
            <button id="dialogSpecOK" type="button" class="btn btn-primary" data-loading-text="保存...">保 存</button>
        </div>

    </div>
</div>

<th:block th:include="include :: footer"/>

<script language="JavaScript" th:inline="none">
    function getSpec() {
        var specs = [];
        $("#dialogSpec").find("div .spec").each(function () {
            var self = $(this);
            var spec = {};
            var spec_values = [];
            spec.spec_name = $(this).attr("data-spec-name");
            spec.spec_id = $(this).attr("data-spec-id");
            self.find("div .vl").each(function () {
                var v = {};
                v.spec_name = spec.spec_name;
                v.spec_id = spec.spec_id;
                var chk = false;
                $(this).find("input[type=checkbox]").each(function () {
                    v.spec_value_id = $(this).val();
                    v.spec_value_name = $(this).attr("title");
                    chk = $(this).prop("checked");
                });
                if (chk) {
                    spec_values.push(v);
                    spec.spec_values = spec_values;
                }
            });
            if (spec_values.length > 0) {
                specs.push(spec);
            }

        });
        return specs;
    }

    function getProducts(specs) {

        if (!specs || specs.length == 0) {
            return [];
        } else {

            return joinSpec([[]], specs, 0, specs.length - 1);
        }

        function joinSpec(prevProducts, specs, i, max) {
            var currentProducts = [], currentProduct, currentSpecs = specs[i];
            if (i > max) {
                return prevProducts;
            }
            $.each(prevProducts, function (i, prevProduct) {
                $.each(currentSpecs, function (j, spec) {
                    currentProduct = prevProduct.slice(0);
                    currentProduct.push(spec);
                    currentProducts.push(currentProduct);
                });
            });
            return joinSpec(currentProducts, specs, ++i, max);
        }
    }
</script>
<script language="JavaScript" th:inline="javascript">
    $(document).ready(function () {
        var valueSpec = [];
        if ([[${type}]] == 1) {
            var proStr = JSON.parse(sessionStorage.getItem("products"));
            console.log("子页面取sessionStorage的值");
            console.log(proStr);
            console.log(proStr.length);
            if (proStr == undefined || proStr == null || proStr == '') {

            } else {
                // var pList ='';
                for (var i = 0; i < proStr.length; i++) {
                    var str = "<tr>";
                    str += "<td>" + proStr[i].spec + "</td>";
                    str += "<td>" +
                        "<div style='float: left'>" +
                        "<button type='button' class='layui-btn upload' id=" + i + ">上传图片</button> </div>" +
                        "<input type='hidden' id='icon-" + i + "' name='icon' value='"+proStr[i].icon+"'>" +
                        "<div id='show-" + i + "'>" +
                        "<img src='"+proStr[i].icon+"' style='width:80px;height:80px;'>" +
                        "</div>" +
                        "</td>";

                    str += "<td style='text-align: left;width: 150px;'>" +
                        "<div style='float: left'>" +
                        "<input name='priceO' type='text' value='" + proStr[i].priceO + "' class='form-control' style='height: 22px;width: 60px;padding: 0 2px;'></div>" +
                        "</td>";
                    str += "<td style='text-align: left;width: 150px;'>" +
                        "<div style='float: left'>" +
                        "<input name='priceN' type='text' value='" + proStr[i].priceN + "' class='form-control' style='height: 22px;width: 60px;padding: 0 2px;'></div>" +
                        "</td>";
                    str += "<td><input name='stock' type='text' class='form-control' value='" + proStr[i].stock + "' style='height: 22px;width: 60px;padding: 0 2px;'></td>";
                    if (proStr[i].isDefault) {
                        str += "<td><input name='isDefault' type='radio' checked></td>";
                    } else {
                        str += "<td><input name='isDefault' type='radio'></td>";
                    }
                    /* str+="<td><a class='delSpec' href='javascript:;' style='color: #428bca'>删除</a></td>"; */

                    $("#plist tbody").append(str);

                    var specSelect = proStr[i].spec.split("*");
                    console.log("spec-----------");
                    console.log(specSelect);
                    for (var j = 0; j < specSelect.length; j++) {
                        var specValueSelect = specSelect[j].split(":");
                        console.log("值------------");
                        valueSpec.push(specValueSelect[1]);

                        // $("#spec input[title='"+specValueSelect[1]+"']").prop("checked",true);
                        // $("#spec").find("input[type=checkbox][title='"+specValueSelect[1]+"']").prop("checked",true);
                    }
                }

                layui.use('upload', function () {
                    var $ = layui.jquery
                        , upload = layui.upload;

                    //普通图片上传
                    var uploadInst = upload.render({
                        elem: '.upload'
                        , url: ctx+'/common/upload' //改成您自己的上传接口
                        , done: function (res) {
                            console.log(this.item)
                            //如果上传失败
                            if (res.code > 0) {
                                return layer.msg('上传失败');
                            }
                            //上传成功
                            $("#show-" + this.item[0].id).html("<img src='" + res.url + "' style='width:80px;height:80px;'>");
                            $("#icon-" + this.item[0].id).val(res.url);
                        }
                        , error: function () {
                            //演示失败状态，并实现重传
                            var demoText = $('#show-' + i);
                            demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                            demoText.find('.demo-reload').on('click', function () {
                                uploadInst.upload();
                            });
                        }
                    });
                });
                var spec = '';
                for (o in [[${specList}]]) {

                    spec += '<div class="spec" th:each="spList : ${specList}" style="float: left;padding-right: 10px;" ' +
                        'data-spec-name="' + [[${specList}]][o].goodsSpec.name + '"data-spec-id="' + [[${specList}]][o].goodsSpec.id + '"   >\n' +
                        '<span class="h5 mb10" style="float: left">' +
                        '<input class="specChkAll" type="checkbox">' +
                        '<strong >' + [[${specList}]][o].goodsSpec.name + '</strong></span>\n' +
                        '<div style="float: left;padding-left: 20px;">\n';

                    console.log("三连-----------------");
                    console.log([[${specList}]]);
                    console.log([[${specList}]][o]);
                    console.log([[${specList}]][o].specValList);
                    var specValList = [[${specList}]][o].typeSpecValueDtoList;


                    for (p in specValList) {
                        if (isInArray(valueSpec, specValList[p].value)) {
                            spec += '<div class="vl"  >\n' +
                                '<input id="' + specValList[p].specValueId + '" type="checkbox" value="' + specValList[p].specValueId + '"\n' +
                                'title="' + specValList[p].value + '" checked><span >' + specValList[p].value + '</span>\n' +
                                '</div>';
                        } else {
                            spec += '<div class="vl"  >\n' +
                                '<input id="' + specValList[p].specValueId + '" type="checkbox" value="' + specValList[p].specValueId + '"\n' +
                                'title="' + specValList[p].value + '"><span >' + specValList[p].value + '</span>\n' +
                                '</div>';
                        }

                    }
                    spec += '</div></div>';

                }
                $("#specParent").html(spec);

            }
        }

        $(".specChkAll").on("click", function () {
            if ($(this).prop("checked")) {
                $(this).parent().parent().find("input[type=checkbox]").each(function () {
                    $(this).prop("checked", true);
                });
            } else {
                $(this).parent().parent().find("input[type=checkbox]").each(function () {
                    $(this).prop("checked", false);
                });
            }
        });
        $("#plist .delSpec").on("click", function () {
            $(this).parent().parent().remove();
        });
        $("#doProduct").on("click", function () {
            var specs = getSpec();
            console.log(specs);
            var product_name = [];
            var spec_values = [];
            var size = 1;
            $.each(specs, function (i, s) {
                size = size * s.spec_values.length;
                var t = [];
                $.each(s.spec_values, function (j, o) {
                    t.push(o);
                });
                spec_values.push(t);
            });
            $.each(getProducts(spec_values), function (i, v) {
                var n = "";
                $.each(v, function (j, s) {
                    n = n + s.spec_name + ":" + s.spec_value_name;
                    if (j < v.length - 1) n += "*";
                });
                product_name.push(n);
            });
            if (spec_values.length < 1) {
                layer.alert("请选择一种规格");
                return false;
            }
            if (spec_values.length > 1) {
                layer.alert("只能选择一种规格");
                return false;
            }
            //console.log("product_name::"+JSON.stringify(product_name));
            $("#plist tbody").html("");
            var i = 0;
            var priceO = [[${priceO}]] || '';
            var priceN = [[${priceN}]] || '';
            var priceVip = [[${priceVip}]] || '';
            var stock = [[${stock}]] || '';
            $.each(product_name, function (i, name) {
                i++;
                var str = "<tr >";
                str += "<td>" + name + "</td>";
                str += "<td>" +
                    "<div style='float: left'>" +
                    "<button type='button' class='layui-btn upload' id=" + i + ">上传图片</button> </div>" +
                    "<input type='hidden' id='icon-" + i + "' name='icon'>" +
                    "<p id='show-" + i + "'></p>" +
                    "</td>";

                str += "<td style='text-align: left;width: 150px;'>" +
                    "<div style='float: left'>" +
                    "<input name='priceO' type='text' value='" + priceO + "' class='form-control' style='height: 22px;width: 60px;padding: 0 2px;'></div>" +
                    "</td>";
                str += "<td style='text-align: left;width: 150px;'>" +
                    "<div style='float: left'>" +
                    "<input name='priceN' type='text' value='" + priceN + "' class='form-control' style='height: 22px;width: 60px;padding: 0 2px;'></div>" +
                    "</td>";
                str += "<td><input name='stock' value='" + stock + "' type='text' class='form-control' style='height: 22px;width: 60px;padding: 0 2px;'></td>";
                str += "<td><input name='isDefault' type='radio'></td>";
                /*  str+="<td><a class='delSpec' href='javascript:;' style='color: #428bca'>删除</a></td>"; */
                $("#plist tbody").append(str);
            })

            layui.use('upload', function () {
                var $ = layui.jquery
                    , upload = layui.upload;

                //普通图片上传
                var uploadInst = upload.render({
                    elem: '.upload'
                    , url: ctx+'/common/upload' //改成您自己的上传接口
                    , done: function (res) {
                        console.log(this.item)
                        //如果上传失败
                        if (res.code > 0) {
                            return layer.msg('上传失败');
                        }
                        //上传成功
                        $("#show-" + this.item[0].id).html("<img src='" + res.url + "' style='width:80px;height:80px;'>");
                        $("#icon-" + this.item[0].id).val(res.url);
                    }
                    , error: function () {
                        //演示失败状态，并实现重传
                        var demoText = $('#show-' + i);
                        demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                        demoText.find('.demo-reload').on('click', function () {
                            uploadInst.upload();
                        });
                    }
                });
            });
            /*  $("#plist .delSpec").on("click",function(){
                 $(this).parent().parent().remove();
             }); */
            $("#plist .member").on("click", function () {
                var self = $(this).parent().find("input[type=hidden]");
            });
        });
        $("#dialogSpecOK").on("click", function () {
            var isDefault = 0;
            $("#plist tbody").find("input[name='isDefault']").each(function () {
                if ($(this).prop("checked")) isDefault++;
            });
            if (isDefault == 1) {
                var specs = getSpec();
                var spec_values = [];
                var size = 1;
                $.each(specs, function (i, s) {
                    size = size * s.spec_values.length;
                    var t = [];
                    $.each(s.spec_values, function (j, o) {
                        t.push(o);
                    });
                    spec_values.push(t);
                });
                parent.$("#spec").val(JSON.stringify(specs));
                var specs = [];
                var specs_name = "";
                $("#plist tbody").find("tr").each(function () {
                    var self = $(this);
                    var spec = self.find("td:first").text();
                    specs_name += spec + "|";
                    var productId = self.find("input[name='productId']").val();
                    var stock = self.find("input[name='stock']").val();
                    var priceO = self.find("input[name='priceO']").val();
                    var priceN = self.find("input[name='priceN']").val();
                    var priceVip = self.find("input[name='priceVip']").val();
                    var icon = self.find("input[name='icon']").val();
                    var isDefault = self.find("input[name='isDefault']").prop("checked") == true;
                    specs.push({
                        'spec': spec,
                        'productId': productId,
                        'stock': stock,
                        'priceO': priceO,
                        'priceN': priceN,
                        'priceVip': priceVip,
                        'isDefault': isDefault,
                        'icon': icon,
                    });
                });
                parent.$("#products").val(JSON.stringify(specs));
                parent.$("#showSpec").hide();
                parent.$("#hhasSpec").val("1");
                sessionStorage.setItem("products", JSON.stringify(specs));
                parent.$("#sp_new").html('<div class="form-group" id="gg_new">' +
                    '<label for="gg_new" class="col-sm-2 control-label">规格</label>' +
                    '<div class="col-sm-8">' +
                    '<button id="specEditBtn" class="btn btn-primary" style="float: left;" onclick="specEditBtn66()" type="button">编辑规格</button>' +
                    '<div style="float: left;text-align: left;">已设置' + specs.length + '个规格货品[' + specs_name + ']</div>' +
                    '</div>' +
                    '</div>').show();
                // parent.$("#specEditBtn").on("click",function(){
                // layer.open({
                // 	type:2,
                // 	title:"编辑规格",
                // 	area : [ '800px' ],
                // 	maxmin:true,
                // 	content:"/beaut/goodsGoods/spec?id="+$("#typeId").val()+"&sku="+$("#sku").val()+"&price="+$("#price").val()+"&priceMarket="+$("#priceMarket").val()+"&weight="+$("#weight").val()
                // })
                // });
                var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
                parent.layer.close(index);
                // $("#dialogSpec").modal("hide");
            } else {
                layer.alert("请选择一个货品为默认货品");
                return false;
            }
        });
    });

    function isInArray(arr, value) {
        for (var i = 0; i < arr.length; i++) {
            if (value === arr[i]) {
                return true;
            }
        }
        return false;
    }

</script>
</body>

</html>
